package com.tbm.console.proj.controller;

import com.tbm.console.base.controller.BaseController;
import com.tbm.console.common.constant.ConsoleConstant;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.proj.entity.*;
import com.tbm.console.proj.service.*;
import com.tbm.console.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@Slf4j
public class IndexController extends BaseController {
    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private LocalUserInfoService localUserInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 重定向
     * @return
     */
    @RequestMapping(value = "/")
    public ModelAndView index(){
        ModelAndView mv  = this.getModelAndView();
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping(value = "/logout_tologout")
    public ModelAndView logout(){
        ModelAndView modelAndView = this.getModelAndView();
        this.getRequest().getSession().removeAttribute(ConsoleConstant.SESSIONUSER);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.RIGHTS);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.ROLEID);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.BUTTONRIGHTS);
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping("/main")
    public ModelAndView main(){
        //获取角色以及menu list
        ModelAndView mv = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            String user = (String) this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER);
            SystemUser systemUser = JsonUtils.jsonToObject(user, SystemUser.class);
            Integer roleId = systemUser.getRoleId();
            //通过Role查找rights，在查menu
            PageData pageData = new PageData();
            pageData.put("id", roleId);
            List<SystemRole> allOrOne = systemRoleService.findAll(pageData);
            if(allOrOne==null||allOrOne.size()==0){
                mv.setViewName("login");
                return mv;
            }
            //为了防止转成科学计数法，将权限码添加了首位标记：R-页面权限，B-按钮权限
            String rights = allOrOne.get(0).getRights().substring(1);
            //通过rights来获取menu
            List<Integer> ids = new ArrayList<>();
            for(int i=1;i<1000;i++){
                if(RightsHelper.testRights(rights, i)){
                    ids.add(i);
                }
            }
            Integer[] idsArray = new Integer[ids.size()];
            for(int i=0;i<ids.size();i++){
                idsArray[i] = ids.get(i);
            }
            //通过ids查询所有的menu
            boolean b = localUserInfoService.checkIsNull(systemUser.getId());
            mv.addObject("flag", b);
            mv.addObject("user",systemUser.getNickname());
            mv.addObject("loginName",systemUser.getUsername());
            mv.addObject("count", 1);
            mv.addObject("shortlist", shortList(systemUser.getId()));
            mv.addObject("menu", menuLists(systemMenuService.findAllById(idsArray)));
            viewName = "index/main";
        }
        mv.setViewName(viewName);
        return mv;
    }

    /**
     * iframe 跳转页面
     * @return
     */
    @RequestMapping(value="/iframe")
    public ModelAndView mainIframe(){
        ModelAndView mv = this.getModelAndView();
        //先查询redis
        //在查询数据库
        PageData menuPd = new PageData();
        menuPd.put("menuType", "report");
        List<SystemMenu> allMenu = systemMenuService.findAll(menuPd);
//        PageData paramPageData = new PageData();
//        paramPageData.put("uploadFlag", InsUpdDelFlagConstant.LOCALLOGPUSHFLAG);
//        List<LocalLog> localLogList = localLogService.findAll(paramPageData);
        List<PageData> list = new ArrayList<>();
        for(SystemMenu menu :allMenu){
            PageData pd = new PageData();
            String key = menu.getMenuURL().substring(menu.getMenuURL().lastIndexOf("/") + 1);
            Integer value = 0;
            pd.put("name", menu.getMenuName());
            pd.put("report", key);
            try{
                value = Integer.valueOf(stringRedisTemplate.opsForValue().get(key));
            }catch (Exception e){
                value = 0;
            }
            pd.put("count", value);
            list.add(pd);
        }
        PageData temp = new PageData();
        temp.put("userId", JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUser.class).getId());
        List<LocalUserInfoEntity> all = localUserInfoService.findAll(temp);

        //如果设置了用户信息
        if(all.size()==1){
            String password = all.get(0).getPassword();
            List<String> strings = new ArrayList<>();
            List<PageData> result = new ArrayList<>();
            if(null==password||"".equals(password)){
                PageData pd = new PageData();
                pd.put("id", "id0");
                result.add(pd);
            }else{
                strings = Arrays.asList(password.split("&"));
                for(int i=0;i<strings.size();i++){
                    PageData pd = new PageData();
                    pd.put("id", strings.get(i));
                    pd.put("chartjs", "chart-" + strings.get(i)+".js");
                    result.add(pd);
                }
            }
            mv.addObject("ids", result);
        }
        mv.addObject("count", list.size());
        mv.addObject("reportList", list);
        mv.setViewName("index/welcome");
        return mv;
    }

    //--------------------------------------------------------------------------//
    private List<PageData> menuLists (List<SystemMenu> systemMenus){
        List<PageData> nodes = new ArrayList<PageData>();
        int i = 0;
        for(SystemMenu menuEntity : systemMenus){
            //获取父目录
            if("0".equals(menuEntity.getParentId())&&InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menuEntity.getDeleteFlag())){
                //获取MENU_ID
                Integer menuId = menuEntity.getId();
                PageData pd = new PageData();
                pd.put("MENU_ID",String.valueOf(menuEntity.getId()));
                pd.put("PARENT_ID",menuEntity.getParentId());
                pd.put("MENU_NAME",menuEntity.getMenuName());
                pd.put("MENU_ICON",menuEntity.getMenuIcon());
                List<PageData> subMenuEntityPageData = new ArrayList<>();

                for(SystemMenu menu:systemMenus){
                    if(menuId == Integer.valueOf(menu.getParentId())&&InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menu.getDeleteFlag())){
                        PageData subPageData = new PageData();
                        subPageData.put("MENU_ID",String.valueOf(menuEntity.getId()));
                        subPageData.put("PARENT_ID",menu.getParentId());
                        subPageData.put("MENU_URL",menu.getMenuURL());
                        subPageData.put("MENU_NAME",menu.getMenuName());
                        subPageData.put("MENU_ICON",menu.getMenuIcon());
                        subPageData.put("ID", i++);
                        subMenuEntityPageData.add(subPageData);
                    }
                }
                pd.put("subMenu",subMenuEntityPageData);
                nodes.add(pd);
            }
        }

        return nodes;
    }

    private List<PageData> shortList(Integer id) {
        PageData temp = new PageData();
        temp.put("userId", id);
        List<LocalUserInfoEntity> all = localUserInfoService.findAll(temp);
        List<PageData> resultList = new ArrayList<>();
        if(all.size()==1){
            List<Integer> idsList = new ArrayList<>();
            for(int i=0;i<200;i++){
                if(RightsHelper.testRights(all.get(0).getUserShortCut().substring(1),i)){
                    idsList.add(i);
                }
            }
            Integer[] idsArray = new Integer[idsList.size()];
            idsList.toArray(idsArray);
            List<SystemMenu> systemMenuList = systemMenuService.findAllById(idsArray);

            for(SystemMenu menu : systemMenuList){
                PageData pageData = new PageData();
                pageData.put("menuName", menu.getMenuName());
                pageData.put("menuUrl", "/" + menu.getMenuURL());
                resultList.add(pageData);
            }
        }else{
        }
        return resultList;
    }
}
